package com.star.starojcodesandbox.controller;


import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.core.DockerClientBuilder;
import com.star.starojcodesandbox.JavaDockerCodeSandbox;
import com.star.starojcodesandbox.JavaDockerCodeSandboxOld;
import com.star.starojcodesandbox.JavaNativeCodeSandbox;
import com.star.starojcodesandbox.model.ExecuteCodeRequest;
import com.star.starojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.ui.context.Theme;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@RestController("/")
public class MainController {


    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";

    private static final String AUTH_REQUEST_SECRET = "secretKey";


    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;

    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCoded(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        String header = request.getHeader(AUTH_REQUEST_HEADER);

        if (!AUTH_REQUEST_SECRET.equals(header)) {
            response.setStatus(403);
            return null;
        }

        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        return javaDockerCodeSandbox.executeCode(executeCodeRequest);
    }

    @GetMapping("/cleanUp")
    public String cleanContainer() {

        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containers = listContainersCmd.withShowAll(true).exec();

        List<String> ids = containers.stream().filter(item -> item.getStatus().startsWith("Up") && item.getImage().equals("openjdk:8-alpine"))
                .map(Container::getId).collect(Collectors.toList());
        for (String id : ids) {
            System.out.println(id);
            StopContainerCmd stopContainerCmd = dockerClient.stopContainerCmd(id);
            stopContainerCmd.exec();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException("容器停止失败");
        }

        for (String id : ids) {
            dockerClient.removeContainerCmd(id).exec();
        }

        return "ok";

    }

    @GetMapping("/cleanExit")
    public String cleanContainerExit() {

        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        List<Container> containers = listContainersCmd.withShowAll(true).exec();

        List<String> ids = containers.stream().filter(item -> item.getStatus().startsWith("Exited") && item.getImage().equals("openjdk:8-alpine"))
                .map(Container::getId).collect(Collectors.toList());

        for (String id : ids) {
            dockerClient.removeContainerCmd(id).exec();
        }

        return "ok";

    }

}
